<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="检验方案编号" prop="templateNo">
        <el-input
          v-model="queryParams.templateNo"
          placeholder="请输入检验方案编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检验方案名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入检验方案名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存货编码" prop="inventoryCode">
        <el-input
          v-model="queryParams.inventoryCode"
          placeholder="请输入存货编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存货名称" prop="inventoryName">
        <el-input
          v-model="queryParams.inventoryName"
          placeholder="请输入存货名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商编码" prop="supplierCode">
        <el-input
          v-model="queryParams.supplierCode"
          placeholder="请输入供应商编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检验类型" prop="inspectionType">
        <el-select v-model="queryParams.inspectionType" placeholder="请选择检验类型" clearable>
          <el-option v-for="opt in inspectionTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="s in dict.type.sys_common_status" :key="s.value" :label="s.label" :value="s.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:template:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange" @expand-change="handleExpandChange" row-key="templateId">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-card shadow="never" class="detail-card" :body-style="{ padding: '8px 12px' }">
            <div class="detail-title">检验项目明细</div>
            <el-table :data="props.row.bizInspectionItemList || []" size="mini" class="compact-detail-table" style="width:auto">
              <el-table-column label="项目序号" prop="itemNo" width="70" align="center" />
              <el-table-column label="检验项目名称" prop="itemName" min-width="140" show-overflow-tooltip />
              <el-table-column label="检验方法" prop="inspectionMethod" width="80" />
              <el-table-column label="检验工具" prop="inspectionTool" width="110" />
              <el-table-column label="验收标准" prop="acceptanceCriteria" min-width="160" show-overflow-tooltip />
              <el-table-column label="标准值" prop="standardValue" width="90" />
              <el-table-column label="上限" prop="upperLimit" width="90" />
              <el-table-column label="下限" prop="lowerLimit" width="90" />
              <el-table-column label="单位" prop="unit" width="80" />
              <el-table-column label="关键" prop="isCritical" width="70">
                <template slot-scope="scope">
                  <el-tag size="mini" :type="scope.row.isCritical === '1' ? 'danger' : 'info'">{{ scope.row.isCritical === '1' ? '是' : '否' }}</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="检验方案ID" align="center" prop="templateId" width="120" />
      <el-table-column label="检验方案编号" align="center" prop="templateNo" min-width="180" />
      <el-table-column label="检验方案名称" align="center" prop="templateName" min-width="240" />
      <el-table-column label="存货编码" align="center" prop="inventoryCode" min-width="180" />
      <el-table-column label="存货名称" align="center" prop="inventoryName" min-width="220" />
      <el-table-column label="供应商编码" align="center" prop="supplierCode" min-width="180" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" min-width="220" />
      <el-table-column label="检验类型" align="center" prop="inspectionType" width="140">
        <template slot-scope="scope">
          <el-tag size="mini">{{ mapInspectionType(scope.row.inspectionType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="抽检比例(%)" align="center" prop="sampleRate" width="120" />
      <el-table-column label="AQL水平" align="center" prop="aqlLevel" width="120" />
      <el-table-column label="检验标准说明" align="center" prop="inspectionStandard" min-width="260" />
      <el-table-column label="合格标准" align="center" prop="qualifiedCriteria" width="140">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.qualifiedCriteria === 'ZERO_DEFECT' ? 'success' : 'warning'">{{ mapQualifiedCriteria(scope.row.qualifiedCriteria) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改检验方案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="860px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 两列布局：每行两个字段 -->
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="检验方案名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入检验方案名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存货编码" prop="inventoryCode">
              <el-select v-model="form.inventoryCode" placeholder="请选择存货编码" filterable @change="onInventoryCodeChange">
                <el-option v-for="inv in inventoryOptions" :key="inv.inventoryCode" :label="inv.inventoryCode + ' - ' + inv.inventoryName" :value="inv.inventoryCode" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="检验类型" prop="inspectionType">
              <el-select v-model="form.inspectionType" placeholder="请选择检验类型">
                <el-option v-for="opt in inspectionTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抽检比例(%)" prop="sampleRate">
              <el-input-number v-model="form.sampleRate" :min="0" :max="100" :step="1" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="AQL水平" prop="aqlLevel">
              <el-input v-model="form.aqlLevel" placeholder="请输入AQL水平" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合格标准" prop="qualifiedCriteria">
              <el-select v-model="form.qualifiedCriteria" placeholder="请选择合格标准">
                <el-option v-for="opt in qualifiedCriteriaOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="检验标准说明" prop="inspectionStandard">
              <el-input v-model="form.inspectionStandard" placeholder="请输入检验标准说明" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">检验项目明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddBizInspectionItem">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteBizInspectionItem">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="bizInspectionItemList" :row-class-name="rowBizInspectionItemIndex" @selection-change="handleBizInspectionItemSelectionChange" ref="bizInspectionItem">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="项目序号" prop="itemNo" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemNo" placeholder="请输入项目序号" />
            </template>
          </el-table-column>
          <el-table-column label="检验项目名称" prop="itemName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemName" placeholder="请输入检验项目名称" />
            </template>
          </el-table-column>
          <el-table-column label="检验方法" prop="inspectionMethod" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.inspectionMethod" placeholder="请选择检验方法">
                <el-option v-for="opt in inspectionMethodOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="检验工具" prop="inspectionTool" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.inspectionTool" placeholder="请输入检验工具" />
            </template>
          </el-table-column>
          <el-table-column label="验收标准" prop="acceptanceCriteria" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.acceptanceCriteria" placeholder="请输入验收标准" />
            </template>
          </el-table-column>
          <el-table-column label="标准值" prop="standardValue" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.standardValue" placeholder="请输入标准值" />
            </template>
          </el-table-column>
          <el-table-column label="上限值" prop="upperLimit" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.upperLimit" placeholder="请输入上限值" />
            </template>
          </el-table-column>
          <el-table-column label="下限值" prop="lowerLimit" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.lowerLimit" placeholder="请输入下限值" />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位" />
            </template>
          </el-table-column>
          <el-table-column label="是否关键项目" prop="isCritical" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isCritical" placeholder="是否关键">
                <el-option label="否" value="0" />
                <el-option label="是" value="1" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/system/template"
import { listInventory } from "@/api/system/inventory"

export default {
  name: "Template",
  dicts: ['sys_common_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBizInspectionItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检验方案表格数据
      templateList: [],
      // 检验项目明细表格数据
      bizInspectionItemList: [],
      // 检验类型与合格标准选项
      inspectionTypeOptions: [
        { value: 'VISUAL', label: '外观检验' },
        { value: 'DIMENSIONAL', label: '尺寸检验' },
        { value: 'PERFORMANCE', label: '性能检验' },
        { value: 'SAFETY', label: '安全检验' }
      ],
      // 检验方法选项（与检验类型一致，用作明细下拉）
      inspectionMethodOptions: [
        { value: 'VISUAL', label: '外观检验' },
        { value: 'DIMENSIONAL', label: '尺寸检验' },
        { value: 'PERFORMANCE', label: '性能检验' },
        { value: 'SAFETY', label: '安全检验' }
      ],
      qualifiedCriteriaOptions: [
        { value: 'ZERO_DEFECT', label: '零缺陷' },
        { value: 'AQL_STANDARD', label: 'AQL标准' }
      ],
      // 存货下拉选项
      inventoryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateNo: null,
        templateName: null,
        inventoryCode: null,
        inventoryName: null,
        supplierCode: null,
        inspectionType: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "请输入检验方案名称", trigger: "blur" }
        ],
        inventoryCode: [
          { required: true, message: "请选择存货编码", trigger: "change" }
        ],
        inspectionType: [
          { required: true, message: "请选择检验类型", trigger: "change" }
        ],
        sampleRate: [
          { required: true, message: "请输入抽检比例", trigger: "blur" }
        ],
        qualifiedCriteria: [
          { required: true, message: "请选择合格标准", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.loadInventoryOptions()
  },
  methods: {
    /** 查询检验方案列表 */
    getList() {
      this.loading = true
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        templateNo: null,
        templateName: null,
        inventoryCode: null,
        inventoryName: null,
        supplierCode: null,
        supplierName: null,
        inspectionType: null,
        sampleRate: null,
        aqlLevel: null,
        inspectionStandard: null,
        qualifiedCriteria: null,
        status: '0',
        remark: null,
        delFlag: null
      }
      this.bizInspectionItemList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    mapInspectionType(val) {
      const m = { VISUAL: '外观检验', DIMENSIONAL: '尺寸检验', PERFORMANCE: '性能检验', SAFETY: '安全检验' }
      return m[val] || val || '-'
    },
    mapQualifiedCriteria(val) {
      const m = { ZERO_DEFECT: '零缺陷', AQL_STANDARD: 'AQL标准' }
      return m[val] || val || '-'
    },
    /** 加载存货下拉 */
    loadInventoryOptions() {
      const params = { pageNum: 1, pageSize: 9999 }
      listInventory(params).then(res => {
        this.inventoryOptions = res && res.rows ? res.rows : []
      })
    },
    /** 选择存货编码时联动名称 */
    onInventoryCodeChange(code) {
      const hit = this.inventoryOptions.find(i => i.inventoryCode === code)
      this.form.inventoryName = hit ? hit.inventoryName : ''
    },
    /** 行展开时加载明细（首次展开时拉取，收起不重复加载） */
    handleExpandChange(row, expanded) {
      // 如果第二参数为布尔值且是收起，则直接返回
      if (typeof expanded === 'boolean' && expanded === false) return
      // 已加载过则不再重复请求
      if (Array.isArray(row.bizInspectionItemList) && row.bizInspectionItemList.length >= 0) return
      // 拉取详情并填充明细列表
      const id = row.templateId
      if (!id) return
      getTemplate(id).then(res => {
        const items = (res && res.data && res.data.bizInspectionItemList) ? res.data.bizInspectionItemList : []
        this.$set(row, 'bizInspectionItemList', items)
      }).catch(() => {
        // 失败兜底，避免二次加载误判
        this.$set(row, 'bizInspectionItemList', [])
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加检验方案"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const templateId = row.templateId || this.ids
      getTemplate(templateId).then(response => {
        this.form = response.data
        this.bizInspectionItemList = response.data.bizInspectionItemList
        this.open = true
        this.title = "修改检验方案"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.bizInspectionItemList = this.bizInspectionItemList
          if (this.form.templateId != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids
      this.$modal.confirm('是否确认删除检验方案编号为"' + templateIds + '"的数据项？').then(function() {
        return delTemplate(templateIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** 检验项目明细序号 */
    rowBizInspectionItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 检验项目明细添加按钮操作 */
    handleAddBizInspectionItem() {
      let obj = {}
      obj.templateNo = ""
      obj.itemNo = ""
      obj.itemName = ""
      obj.inspectionMethod = "VISUAL"
      obj.inspectionTool = ""
      obj.acceptanceCriteria = ""
      obj.standardValue = ""
      obj.upperLimit = ""
      obj.lowerLimit = ""
      obj.unit = ""
      obj.isCritical = "0"
      obj.remark = ""
      this.bizInspectionItemList.push(obj)
    },
    /** 检验项目明细删除按钮操作 */
    handleDeleteBizInspectionItem() {
      if (this.checkedBizInspectionItem.length == 0) {
        this.$modal.msgError("请先选择要删除的检验项目明细数据")
      } else {
        const bizInspectionItemList = this.bizInspectionItemList
        const checkedBizInspectionItem = this.checkedBizInspectionItem
        this.bizInspectionItemList = bizInspectionItemList.filter(function(item) {
          return checkedBizInspectionItem.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleBizInspectionItemSelectionChange(selection) {
      this.checkedBizInspectionItem = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped>
/* 展开明细：卡片按内容宽度显示，减少横向空白 */
.detail-card {
  display: inline-block;
}
.detail-title {
  margin-bottom: 4px;
  font-size: 13px;
  color: #606266;
}
/* 紧凑表格：减小单元格内边距 */
.compact-detail-table ::v-deep .el-table__cell {
  padding: 4px 6px;
}
.compact-detail-table ::v-deep .el-table__body-wrapper {
  overflow: visible;
}
</style>
